package org.projectname.service.admin.manager;

import java.util.ArrayList;
import java.util.List;

import org.hishenframework.core.data.jdbc.template.DataPaging;
import org.hishenframework.core.data.jdbc.template.JdbcOperater;
import org.projectname.entity.manager.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class ResourceService extends JdbcOperater<Resource>{
	
	public void search(DataPaging<Resource> dataPaging, String resource){
		StringBuilder sql = new StringBuilder("SELECT * FROM t_system_resource WHERE 1 = 1 ");
		List<Object> values = new ArrayList<>();
		if(resource != null){
			sql.append(" AND resource = ? ");
			values.add(resource);
		}
		query().qDataPaging(dataPaging, sql.toString(), values.toArray());
	}

	@Override
	public long save(Resource entity) {
		if (isExsit(entity)) {
			return 0;
		}
		return super.save(entity);
	}

	@Override
	public int update(Resource entity) {
		if (isExsit(entity)) {
			return 0;
		}
		return super.update(entity);
	}

	public boolean isExsit(Resource entity) {
		StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM t_system_resource WHERE resource = ?");
		List<Object> values = new ArrayList<>();
		values.add(entity.getResource());
		if(entity.getId() != null){
			sql.append(" AND id <> ?");
			values.add(entity.getId());
		}
		long count = getJdbcTemplate().queryForLong(sql.toString(), values.toArray());
		return count >= 1;
	}
}
